using DemoWebapi01.Entities;
using DemoWebapi01.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace DemoWebapi01.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class RoleController : ControllerBase
    {
        private readonly MyDbContext _context;

        public RoleController(MyDbContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 创建新角色
        /// </summary>
        [HttpPost]
        [Authorize(Roles = "管理员")]
        public async Task<ActionResult<Role>> CreateRole(CreateRoleRequest request)
        {
            // 参数验证
            if (string.IsNullOrEmpty(request.RoleName))
            {
                return BadRequest("角色名称不能为空");
            }

            // 检查角色名是否已存在
            if (_context.Roles.Any(r => r.RoleName == request.RoleName))
            {
                return BadRequest("角色名称已存在");
            }

            // 创建新角色
            var role = new Role
            {
                RoleName = request.RoleName,
                Description = request.Description,
            };

            _context.Roles.Add(role);
            await _context.SaveChangesAsync();

            return Ok(role);
        }

        /// <summary>
        /// 获取所有角色列表
        /// </summary>
        [HttpGet]
        public async Task<ActionResult<List<Role>>> GetRoles()
        {
            var roles = _context.Roles.ToList();
            return Ok(roles);
        }

        /// <summary>
        /// 删除角色
        /// </summary>
        [HttpDelete("{id}")]
        [Authorize(Policy = "AdminOnly")]
        public async Task<ActionResult> DeleteRole(int id)
        {
            var role = await _context.Roles.FindAsync(id);
            if (role == null)
            {
                return NotFound("角色不存在");
            }

            _context.Roles.Remove(role);
            await _context.SaveChangesAsync();

            return Ok("角色删除成功");
        }
    }
}